package com.lml.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @date 2020/3/20 17:18
 * Description:
 */
public class DemoTest03 {

    public static void main(String[] args) {
        //"abcabcd" "bbbbb" "pwkewe"
        String testStr = "pwkewe";
        int i = lengthOfLongestSubstring(testStr);
        System.out.println(i);
    }

    /**
     * 3. 无重复字符的最长子串
     * https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
     *
     * @param s 字符串
     * @return 子字符串的最长长度
     */
    static int lengthOfLongestSubstring(String s) {
        if (s.trim().isEmpty()) {
            return 0;
        }
        char[] charArray = s.toCharArray();
        List<Character> list = new ArrayList<>();
        //将第一个字符放入,用第一个字符和之后的字符进行比较
        list.add(charArray[0]);
        //用来存放每个子字符串长度
        List<Integer> lengthsList = new ArrayList<>();
        for (int i = 1; i < s.length(); i++) {
            if (list.contains(charArray[i])) {
                lengthsList.add(list.size());
                list.clear();
            }
            list.add(charArray[i]);
            if (i == s.length() - 1) {
                lengthsList.add(list.size());
            }
        }
        //从大到小进行排序,输出第一个
        lengthsList.sort((x, y) -> y - x);
        return lengthsList.get(0);
    }

}
